package com.example.onlinemarket.controller;

import com.example.onlinemarket.bean.*;
import com.example.onlinemarket.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
public class InfoController {
    private UserService userService;
    private GoodService goodService;
    private OrderService orderService;
    private OrderItemService orderItemService;
    @Autowired
    public void setOrderItemService(OrderItemService orderItemService) { this.orderItemService = orderItemService; }
    @Autowired
    public void setOrderService(OrderService orderService) { this.orderService = orderService; }
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }
    @Autowired
    public void setGoodService(GoodService goodService) { this.goodService = goodService; }

    private Logger logger;
    @Autowired
    public void setLogger() {this.logger = LoggerFactory.getLogger(InfoController.class);}

    @RequestMapping("/")
    public String hello(){
        return "Hello";
    }

    @GetMapping("/userInfo")
    public String showUserInfo(){ return "pages/userInfo"; }

    @RequestMapping("/get/goodImg/{goodId}")
    public void getGoodImg(HttpSession session, HttpServletResponse response, @PathVariable("goodId")Integer goodId) throws IOException {
        Good good = goodService.getGoodById(goodId);
        if((good.isStatus())||(session.getAttribute("userId").equals(good.getUserId()))) {
            byte[] photo = good.getPhoto();
            if(photo!=null) {
                response.setContentType("image/jpeg");
                OutputStream os = response.getOutputStream();
                os.write(photo);
                os.flush();
                os.close();
            }
        }else{
            System.out.println("非法操作5！用户正在试图获取非专属鲜花信息！");
            // TODO: 2021/1/8 非法操作处理
        }
    }

    @RequestMapping("/update/updateNote")
    public String updateNote(HttpSession session, Integer orderId, Integer goodId, String note){
        User loginUser = (User) session.getAttribute("loginUser");
        Order shoppingCart = orderService.getUserShoppingOrder(loginUser.getUserId());
        if(!loginUser.isRole()) {
            if (shoppingCart.getUserId().equals(loginUser.getUserId())) {
                boolean flag = orderItemService.updateGoodNote(orderId, goodId, note);
                System.out.println(flag?"更新鲜花备注成功":"更新鲜花备注失败");
                return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/true";
            } else {
                System.out.println("非法操作8！不能操作其他用户的购物车！");
                return "pages/shopping/shoppingIndex";
            }
        }else{
            System.out.println("非法操作9！商家不能操作购物车！");
            return "pages/shopping/shoppingIndex";
        }
    }

    @RequestMapping("/update/updateGoodNum")
    public String updateGoodNum(HttpSession session, Integer orderId, Integer goodId, Integer goodNum){
        User loginUser = (User) session.getAttribute("loginUser");
        Order shoppingCart = orderService.getUserShoppingOrder(loginUser.getUserId());
        if(!loginUser.isRole()) {
            if (shoppingCart.getUserId().equals(loginUser.getUserId())) {
                if(goodService.isGoodNumLegal(goodNum, goodId)) {
                    boolean flag = orderItemService.updateGoodNum(orderId, goodId, goodNum);
                    System.out.println(flag?"更新鲜花数量成功":"更新鲜花数量失败");
                    return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/true";
                }else{
                    System.out.println("非法操作10，数量非法！");
                    return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/true";
                }
            } else {
                System.out.println("非法操作8！不能操作其他用户的购物车！");
                return "pages/shopping/shoppingIndex";
            }
        }else{
            System.out.println("非法操作9！商家不能操作购物车！");
            return "pages/shopping/shoppingIndex";
        }
    }

    @RequestMapping("/get/goodInfo/{goodId}")
    public String getGoodInfo(SearchItem searchItem, HttpSession session, Model model, @PathVariable("goodId")Integer goodId){
        boolean flag = goodService.isGoodExist(goodId);
        User user = (User) session.getAttribute("loginUser");
        if(user.isRole()) {
            if (flag) {
                Good good = goodService.getGoodById(goodId);
                if (session.getAttribute("userId").equals(good.getUserId())) {
                    model.addAttribute("updateGood", good);
                } else {
                    System.out.println("非法操作0！用户正在试图获取非专属鲜花信息！");
                    // TODO: 2021/1/8 非法操作处理
                }
            } else {
                System.out.println("鲜花不存在");
                // TODO: 2021/1/8 鲜花不存在
            }
            return "pages/update/goodInfo";
        }else{
            if(flag) {
                Good good = goodService.getGoodById(goodId);
                User shop = userService.getUserById(good.getUserId());
                model.addAttribute("good", good);
                model.addAttribute("shop", shop);
            }else{
                System.out.println("查询鲜花不存在！");
                // TODO: 2021/1/10 非法查询处理
            }
            model.addAttribute("searchItem", searchItem);
            return "pages/shopping/goodResult";
        }
    }

    //更新鲜花信息
    @RequestMapping("/update/updateGood")
    public String updateGoodInfo(Model model, HttpSession session, Good good, @RequestParam("img")MultipartFile file) throws IOException {
        //必须是本人操作
        if(session.getAttribute("userId").equals(good.getUserId())) {
            //鲜花名和鲜花类型不能为空，进价和售价不能为空且要大于0
            if(!good.getGoodName().equals("")
                    &&!good.getSpecies().equals("鲜花类型")
                    &&good.getSellPrice()!=null&&good.getSellPrice()>0
                    &&good.getPurchasePrice()!=null&&good.getPurchasePrice()>0){
                boolean flag;
                //若库存数量为空或小于0则取0
                if (good.getQuantity()==null||good.getQuantity() < 0) {
                    good.setQuantity(0);
                }
                //根据是否上传图片决定数据库操作
                if (!file.isEmpty()) {
                    InputStream is = file.getInputStream();
                    flag = goodService.updateGoodInfo(good, is);
                }else{
                    flag = goodService.updateGoodInfoWithoutImg(good);
                }
                System.out.println(flag?"更新成功":"更新失败");
            }else{
                model.addAttribute("updateGood", good);
                model = goodService.setErrorInfo(model, good.getGoodName(), good.getSpecies(), good.getSellPrice(), good.getPurchasePrice());
                return "forward:/get/goodInfo/"+good.getGoodId();
            }
        }else{
            System.out.println("非法操作1！用户正在试图获取非专属鲜花信息！");
            // TODO: 2021/1/8 非法操作处理
        }
        return "forward:/shop/shopIndex";
    }

    @RequestMapping("/get/userImg/{userName}")
    public void getUserImg(@PathVariable("userName")String userName, HttpServletResponse response) throws IOException {
        User user = userService.getUserByName(userName);
        byte[] photo = user.getPhoto();
        if(photo != null) {
            response.setContentType("image/jpeg");
            OutputStream os = response.getOutputStream();
            os.write(photo);
            os.flush();
            os.close();
        }
    }

    @RequestMapping("/update/updateUserInfo")
    public String updateUserInfo(){
        return "pages/update/updateUserInfo";
    }

    //鲜花上/下架
    @RequestMapping("/update/goodUpshelfOrDownShelf/{goodId}/{goodStatus}")
    public String goodUpshelfOrDownShelf(HttpSession session, @PathVariable("goodId")Integer goodId, @PathVariable("goodStatus")boolean goodStatus){

        if (goodService.isGoodExist(goodId)) {//确保鲜花存在
            Good good = goodService.getGoodById(goodId);
            if (good.isStatus()!=goodStatus) {//当鲜花状态与目标状态不一致时
                if (session.getAttribute("userId").equals(good.getUserId())) {//确保是本人操作
                    boolean isUpdated = goodService.updateGoodStatus(goodId, goodStatus);
                    logger.debug(isUpdated? "鲜花状态更新成功" : "鲜花状态更新失败");
                } else {
                    System.out.println("非法操作2！用户正在试图更改非专属鲜花信息！");
                    // TODO: 2021/1/8 非法操作处理
                }
            }
        }else{
            logger.debug("操作的鲜花ID不存在!");
        }
        return "forward:/shop/shopIndex";
    }

    @RequestMapping("/update/delGood/{goodId}")
    public String delGood(HttpSession session, @PathVariable("goodId") Integer goodId){
        boolean flag = goodService.isGoodExist(goodId);
        if (flag) {
            Good good = goodService.getGoodById(goodId);
            if (good != null) {
                if (session.getAttribute("userId").equals(good.getUserId())) {
                    flag = goodService.delGoodById(goodId);
                } else {
                    System.out.println("非法操作4！用户正在试图更改非专属鲜花信息！");
                    // TODO: 2021/1/8 非法操作处理
                }
            } else {
                System.out.println("鲜花不存在");
                // TODO: 2021/1/8 鲜花不存在
            }
        }
        return "forward:/shop/shopIndex";
    }

    //修改个人信息
    @RequestMapping("/update/updateUser")
    public String updateUser(HttpSession session, User user, @RequestParam("img") MultipartFile file) throws IOException {
        User loginUser = (User) session.getAttribute("loginUser");
        //若用户提交的密码或邮箱为空则使用之前的数据
        if(user.getPassword()==null||user.getPassword().equals(""))
            user.setPassword(loginUser.getPassword());
        if(user.getEmail()==null||user.getEmail().equals(""))
            user.setEmail(loginUser.getEmail());
        if(user.getEmail()==null||user.getEmail().equals(""))
            user.setEmail(loginUser.getEmail());
        if(user.getAddress()==null||user.getAddress().equals(""))
            user.setAddress(loginUser.getAddress());
        user.setUserName(loginUser.getUserName());
        //根据用户是否上传头像选择不同的数据库操作
        boolean flag;
        if(!file.isEmpty()) {
           InputStream is = file.getInputStream();
           flag = userService.updateUserInfoWithImg(user, is);
        }else
            flag = userService.updateUserInfoWithoutImg(user);
        if(flag){
            loginUser = userService.getUserByName(loginUser.getUserName());
            session.setAttribute("loginUser",loginUser);
            session.setAttribute("userImg", loginUser.getPhoto());
        }
        //根据用户身份返回买家或卖家首页
        return loginUser.isRole()?"forward:/shop/shopIndex":"forward:/shopping/shoppingIndex";
    }

    @RequestMapping("/search/search")
    public String search(Model model, SearchItem searchItem, @RequestParam("currentPage")Integer currentPage, @RequestParam("pageSize")Integer pageSize){
        model.addAttribute("searchItem", searchItem);
        if(searchItem.getSearchSelect().equals("搜索商家")){
            model = userService.userSearch(model, currentPage, pageSize, searchItem.getSearchContent());
            return "pages/search/userSearch";
        }else{
            model = goodService.goodSearch(model, currentPage, pageSize, searchItem.getSearchContent(), searchItem.getSpecies());
            return "pages/search/goodSearch";
        }
    }

    @RequestMapping("/search/get/users/{searchContent}/{pageNum}/{pageSize}")
    public String getUsers(Model model, @PathVariable("searchContent") String searchContent, @PathVariable("pageNum") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        SearchItem searchItem = new SearchItem("搜索商家","鲜花类型", searchContent);
        model.addAttribute("searchItem", searchItem);
        model = userService.userSearch(model, currentPage, pageSize, searchContent);
        logger.debug(model.toString());
        return "pages/search/userSearch";
    }

    @RequestMapping("/search/get/goods/{searchContent}/{species}/{pageNum}/{pageSize}")
    public String getGoods(Model model, @PathVariable("searchContent") String searchContent, @PathVariable("species") String species, @PathVariable("pageNum") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        SearchItem searchItem = new SearchItem("搜索鲜花", species, searchContent);
        model.addAttribute("searchItem", searchItem);
        model = goodService.goodSearch(model, currentPage, pageSize, searchContent, species);
        return "pages/search/goodSearch";
    }


}
